<?php
namespace common\service;

use common\components\Aes;
use yii;

class PubService
{

    /**
     *
     * @param unknown $url
     * @return mixed
     */
    public static function base64ToImg($base64_image_content, $path)
    {

        //$root = $_SERVER['DOCUMENT_ROOT'].'/'.$path;
        $root = $root = Yii::getAlias('@frontend') . '/web/' . $path;
        $folder = date('Ymd') . "/";

        if (!is_dir($root . $folder)) {
            if (!mkdir($root . $folder, 0777, true)) {
                return ['status' => false, 'msg' => '创建目录失败'];
                //die('创建目录失败...');
            } else {
                //    chmod($root.$folder,0777);
            }
        }
        $pre = rand(999, 9999) . time();

        //保存base64字符串为图片
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            $type = $result[2];
            $newName = $pre . ".{$type}";
            $new_file = $root . $folder . $newName;
            if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))) {

                return $path . $folder . $newName;
            }

        }
    }

    /**
     * @param $url
     * @param $data
     * @return mixed
     */
    public static function myCurl($url,$data)
    { // 模拟获取内容函数
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        if (!empty($_SERVER['HTTP_USER_AGENT'])) {
            curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        }
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_HTTPGET, 1); // 发送一个常规的Post请求
        curl_setopt($curl, CURLOPT_TIMEOUT, 10); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            // echo 'Errno'.curl_error($curl);
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据
    }




    /**
     * 判断用户ip是否是中国ip（未分配或者内网IP 的情况也认为非法ip）
     * @return boolean 是返回 true 否则，反之
     */
    public static function isChineseIp()
    {
        //淘宝获取ip信息的接口
        $taobao_url = "http://ip.taobao.com/service/getIpInfo.php?ip=" . yii::$app->request->userIP;
        $res = self::myCurl($taobao_url);
        $res_arr = json_decode($res, true);
        if ($res_arr['code'] == 1) {//ip格式不正确的情况
            return false;
        } elseif ($res_arr['code'] == 0) {
            if (strtolower($res_arr['data']['country_id']) != 'cn') {
                return false;
            } else {
                return true;
            }
        }
    }



    /**
     * 生成自定义长度的字符串
     * @param $length
     * @return null|string
     */
    public static function getRandChar($length)
    {
        $str = null;
        //$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $strPol = "0123456789";
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[mt_rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }



    /**
     * 设置过期时间和返回手机接收码
     * @param $length
     * @return null|string
     */
    public static function getCode($length)
    {
        $session = Yii::$app->session;
        $str = null;
        //$strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $strPol = "0123456789";
        $max = strlen($strPol) - 1;

        for ($i = 0; $i < $length; $i++) {
            $str .= $strPol[rand(0, $max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        $session->set('mcode', $str);
        return $str;

    }



    /**
     * @name 读取excel文件内容
     * @param $filename
     * @param string $encode
     * @return array
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public static function read($filename, $encode = 'utf-8')
    {
        //$objReader = \PHPExcel_IOFactory::createReader('Excel5');
        //$objReader = new \PHPExcel_Reader_Excel2007();
        $objReader = \PHPExcel_IOFactory::createReaderForFile($filename);
        $objReader->setReadDataOnly(true);
        $objPHPExcel = $objReader->load($filename);
        $objWorksheet = $objPHPExcel->getActiveSheet();
        $highestRow = $objWorksheet->getHighestRow();
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString($highestColumn);
        $excelData = array();
        for ($row = 1; $row <= $highestRow; $row++) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                if ($row == 1) {
                    continue;
                }
                $excelData[$row][] = (string)$objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
            }
        }
        return $excelData;
    }

    /**
     * @发送短信，写入日志
     * @param $mobile
     * @param $message
     */
    public static function sendSms($mobile, $message, $sms_signature = '')
    {
        $success = 0;
        if ($sms_signature == '') {
            $sms_signature = yii::$app->params['sms_signature'];
        }
        //准备发送短信
        try {
            $sendRes = \Yii::$app->sm->send($mobile, $message.$sms_signature);
            $resInfo = substr($sendRes->SendSmsTradeResult, 0, 1);
            if ($resInfo >= 1) {
                //发送成功
                $success = 1;
            }
        } catch (\Exception $e) {
            $success = 0;
        }
        //写入短信日志数据
        $data['mobile'] = $mobile;
        $data['sms_content'] = $message;
        $data['send_status'] = $success;
        $data['create_time'] = date('Y-m-d H:i:s',time());
        yii::$app->db->createCommand()->insert('jz_sms_logs',$data)->execute();
        return $success;
    }

    /**
     * @name 踢出用户登陆状态
     * @param $userid
     */
    public static function killOutUser($userid)
    {
        yii::$app->cache->delete('loginFlag_M'.$userid);
        yii::$app->cache->delete('loginFlag_PC'.$userid);
    }


    /**
     * @name aes 加密
     * @param $str
     * @return string
     */
    public static function aes_encode($str)
    {
        $aes = new Aes();
        $aes->set_key(yii::$app->params['aeskey']);
        return urlencode($aes->encrypt($str));
    }

    /**
     * @name aes 解密
     * @param $str
     * @return mixed
     */
    public static function aes_decode($str)
    {
        $aes = new Aes();
        $aes->set_key(yii::$app->params['aeskey']);
        return $aes->decrypt($str);
    }



    /**
     * @name 检查字符长度
     * @param unknown $string
     * @return number
     */
    public static function checkStrLength($string)
    {
        // 将字符串分解为单元
        preg_match_all("/./us", $string, $match);
        // 返回单元个数
        return count($match[0]);
    }


    /**
     * @param int $user_name
     * @param int $user_mobile
     * @param int $exhibition_id
     * @param int $page_id
     * @return mixed
     */
    public static function sendFreeTicket($user_name = 0, $user_mobile = 0, $exhibition_id=0,$page_id=0,$url)
    {
        //post params: exhibition_id,page_id,user_name,user_mobile
        $postArr = [
            'user_name'=>$user_name,
            'user_mobile'=>$user_mobile,
            'exhibition_id' => $exhibition_id,
            'page_id' => $page_id,
        ];
        //生成签名
        /*$appKey = 'rvZlnhglyvqAuPey';
        $sign = md5($appKey.json_encode(ksort($info)));*/
        $res = self::myCurl($url, $postArr);
        return json_decode($res,true);

    }

    //获取浏览器ip地址
    public static function real_ip()
    {
        static $realip;
        if ($realip !== NULL) {
            return $realip;
        }
        if (isset($_SERVER)) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                foreach ($arr as $ip) {
                    $ip = trim($ip);
                    if ($ip != 'unknown') {
                        $realip = $ip;
                        break;
                    }
                }
            }
            else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $realip = $_SERVER['HTTP_CLIENT_IP'];
            }
            else if (isset($_SERVER['REMOTE_ADDR'])) {
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else {
                $realip = '0.0.0.0';
            }
        }
        else if (getenv('HTTP_X_FORWARDED_FOR')) {
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        else if (getenv('HTTP_CLIENT_IP')) {
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else {
            $realip = getenv('REMOTE_ADDR');
        }
        preg_match('/[\\d\\.]{7,15}/', $realip, $onlineip);
        $realip = (!empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0');
        return $realip;
    }

    /**
     * 通过ip地址返回ip所属省市区
     */
    public static function addressIp($ip)
    {
        //淘宝获取ip信息的接口
        $taobao_url = "http://ip.taobao.com/service/getIpInfo.php?ip=" . $ip;
        $res = self::https_request($taobao_url);
        $res_arr = json_decode($res, true);
        if ($res_arr){
            if ($res_arr['data']){
                if ($res_arr['data']['region'] == 'XX' || $res_arr['data']['city'] == 'XX'){
                    $realAddr = $res_arr['data']['ip'];
                }else{
                    $realAddr = $res_arr['data']['region'].$res_arr['data']['city'];
                }
            }else{
                $realAddr = '未知地址';
            }
        }else{
            $realAddr = '未知地址';
        }
        return $realAddr;
    }

    //POST请求函数
    public static function https_request($url,$data = null){
        $curl = curl_init();

        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);

        if(!empty($data)){//如果有数据传入数据
            curl_setopt($curl,CURLOPT_POST,1);//CURLOPT_POST 模拟post请求
            curl_setopt($curl,CURLOPT_POSTFIELDS,$data);//传入数据
        }

        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        $output = curl_exec($curl);
        curl_close($curl);

        return $output;
    }

    /**
     * @name 检查手机号码
     * @param int $mobile
     * @return boolean
     */
    public static function isMobile($mobile)
    {
        if (!is_numeric($mobile)) {
            return false;
        }
        return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,1,3,5,6,7,8]{1}\d{8}$|^18[\d]{9}$#', $mobile) ? true : false;
    }


    public static function Post($curlPost,$url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $return_str = curl_exec($curl);
        curl_close($curl);
        return $return_str;
    }


    public static function xml_to_array($xml){
        $reg = "/<(\w+)[^>]*>([\\x00-\\xFF]*)<\\/\\1>/";
        if(preg_match_all($reg, $xml, $matches)){
            $count = count($matches[0]);
            for($i = 0; $i < $count; $i++){
                $subxml= $matches[2][$i];
                $key = $matches[1][$i];
                if(preg_match( $reg, $subxml )){
                    $arr[$key] = self::xml_to_array( $subxml );
                }else{
                    $arr[$key] = $subxml;
                }
            }
        }
        return $arr;
    }

    /**
     * 是否手机微信
     * @return boolean
     */
    public static function isWeChat()
    {
        if(!self::iswxMobile())return false;
        $ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
        return (preg_match('/MicroMessenger\/([\d.]+)/', $ua, $match)) ? true : false;
    }


    /**
     *
     * 根据php的$_SERVER['HTTP_USER_AGENT'] 中各种浏览器访问时所包含各个浏览器特定的字符串来判断是属于PC还是移动端
     * @author           discuz3x
     * @lastmodify    2014-04-09
     * @return  BOOL
     */
    public static function iswxMobile() {
        global $_G;
        $mobile = array();
        //各个触控浏览器中$_SERVER['HTTP_USER_AGENT']所包含的字符串数组
        static $touchbrowser_list =array('iphone', 'android', 'phone', 'mobile', 'wap', 'netfront', 'java', 'opera mobi', 'opera mini',
            'ucweb', 'windows ce', 'symbian', 'series', 'webos', 'sony', 'blackberry', 'dopod', 'nokia', 'samsung',
            'palmsource', 'xda', 'pieplus', 'meizu', 'midp', 'cldc', 'motorola', 'foma', 'docomo', 'up.browser',
            'up.link', 'blazer', 'helio', 'hosin', 'huawei', 'novarra', 'coolpad', 'webos', 'techfaith', 'palmsource',
            'alcatel', 'amoi', 'ktouch', 'nexian', 'ericsson', 'philips', 'sagem', 'wellcom', 'bunjalloo', 'maui', 'smartphone',
            'iemobile', 'spice', 'bird', 'zte-', 'longcos', 'pantech', 'gionee', 'portalmmm', 'jig browser', 'hiptop',
            'benq', 'haier', '^lct', '320x320', '240x320', '176x220');
        //window手机浏览器数组【猜的】
        static $mobilebrowser_list =array('windows phone');
        //wap浏览器中$_SERVER['HTTP_USER_AGENT']所包含的字符串数组
        static $wmlbrowser_list = array('cect', 'compal', 'ctl', 'lg', 'nec', 'tcl', 'alcatel', 'ericsson', 'bird', 'daxian', 'dbtel', 'eastcom',
            'pantech', 'dopod', 'philips', 'haier', 'konka', 'kejian', 'lenovo', 'benq', 'mot', 'soutec', 'nokia', 'sagem', 'sgh',
            'sed', 'capitel', 'panasonic', 'sonyericsson', 'sharp', 'amoi', 'panda', 'zte');
        $pad_list = array('pad', 'gt-p1000');
        $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if(self::dstrpos($useragent, $pad_list)) {
            return false;
        }
        if(($v = self::dstrpos($useragent, $mobilebrowser_list, true))){
            $_G['mobile'] = $v;
            return true;
        }
        if(($v = self::dstrpos($useragent, $touchbrowser_list, true))){
            $_G['mobile'] = $v;
            return true;
        }
        if(($v = self::dstrpos($useragent, $wmlbrowser_list))) {
            $_G['mobile'] = $v;
            return true; //wml版
        }
        $brower = array('mozilla', 'chrome', 'safari', 'opera', 'm3gate', 'winwap', 'openwave', 'myop');
        if(self::dstrpos($useragent, $brower)) return false;
        $_G['mobile'] = 'unknown';
        //对于未知类型的浏览器，通过$_GET['mobile']参数来决定是否是手机浏览器
        if(isset($_G['mobiletpl'][$_GET['mobile']])) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 判断$arr中元素字符串是否有出现在$string中
     * @param  $string     $_SERVER['HTTP_USER_AGENT']
     * @param  $arr          各中浏览器$_SERVER['HTTP_USER_AGENT']中必定会包含的字符串
     * @param  $returnvalue 返回浏览器名称还是返回布尔值，true为返回浏览器名称，false为返回布尔值【默认】
     * @author           discuz3x
     * @lastmodify    2014-04-09
     */
    public static function dstrpos($string, $arr, $returnvalue = false) {
        if(empty($string)) return false;
        foreach((array)$arr as $v) {
            if(strpos($string, $v) !== false) {
                $return = $returnvalue ? $v : true;
                return $return;
            }
        }
        return false;
    }

}